<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isSongSheet ? '新建歌单' : '添加到歌单'"
    width="40%"
    :close-on-click-modal="false"
  >
    <!-- 添加歌单 -->
    <div v-if="!isSongSheet">
      <div class="top cursor_class" @click="addSongSheet">
        <el-icon :size="20">
          <CirclePlus />
        </el-icon>
        &nbsp;&nbsp;新歌单
      </div>
      <div class="bottom cursor_class" v-for="(item, index) in playlist" :key="index" @click="handleClick(item.id)">
        <img :src="item.coverImgUrl" alt="" />
        <div class="context">
          <div class="title">{{ index === 0 ? "我喜欢的音乐" : item.name }}</div>
          <div>{{ item.trackCount }}首</div>
        </div>
      </div>
    </div>
    <!-- 新建歌单 -->
    <div v-else>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        status-icon
      >
        <el-form-item label="歌单名" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="isSongSheet">
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >新建</el-button
        >
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as myMusicApi from '@/api/my-music'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
const router = useRouter()
const { proxy }: any = getCurrentInstance()
const dialogVisible = ref(false)
const isSongSheet = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  name: '',
})
const playlist = ref<any>([])
const id = ref(0)
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '歌单名不能为空', trigger: 'blur' },
  ]
})
const emit = defineEmits(['handleAddSuccess'])
defineExpose({
  id,
  dialogVisible,
  isSongSheet,
  init: () => init()
})
// 初始化
const init = async () => {
  try {
    playlist.value = []
    let userInfo = proxy.$getUserInfo()
    if (userInfo) {
      // 新建歌单不用请求
      if(!isSongSheet.value){
        const data: any = await myMusicApi.playlist({ uid: userInfo.userId })
        data.playlist.forEach((item: any) => {
          if (item.creator.userId === userInfo.userId) {
            // 我创建的歌单
            playlist.value.push(item)
          }
        })
      }
    } else {
      ElMessage({
        message: '请先登录',
        type: 'error',
      })
      id.value = 0
      dialogVisible.value = false
      isSongSheet.value = false
    }
  } catch (error) {
    console.log(error);
  }
}
const addSongSheet = () => {
  isSongSheet.value = true
}
// 新建歌单并收藏歌曲
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let cookie = localStorage.getItem('cookie')
      const data: any = await myMusicApi.playlistCreate({ name: ruleForm.name, cookie })
      if(id.value){
        await myMusicApi.tracks({ op:'add', pid: data.id , tracks: id.value, cookie })
        ElMessage({
          message: '收藏成功',
          type: 'success',
        })
      }
      // 刷新有延迟
      emit('handleAddSuccess')
      dialogVisible.value = false
    }
  })
}
// 收藏歌曲到歌单
const handleClick = async (pid: number) => {
  try {
    let cookie = localStorage.getItem('cookie')
    await myMusicApi.tracks({ op:'add', pid, tracks: id.value, cookie })
    ElMessage({
      message: '收藏成功',
      type: 'success',
    })
    // 刷新有延迟
    emit('handleAddSuccess')
    dialogVisible.value = false
  } catch (error) {
    console.log(error);
  }
}
</script>
<style lang="scss" scoped>
.top {
  display: flex;
  align-items: center;
  background: #e6e6e6;
  padding: 10px 0 10px 15px
}
.bottom {
  &:hover {
    background: #e6e6e6;
  }
  padding: 6px 10px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  img {
    width: 40px;
    height: 40px;
    object-fit: cover;
  }
  .context {
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    font-size: 12px;
    justify-content: space-around;
    .title {
      color: #000;
    }
  }
}
</style>
